<?php

declare(strict_types=1);

namespace App\Middleware;


use Hyperf\Di\Annotation\Inject;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Hyperf\HttpServer\Contract\ResponseInterface as HttpResponse;
use Hyperf\HttpServer\Contract\RequestInterface;
use Psr\Container\ContainerInterface;
use Qbhy\HyperfAuth\AuthManager;

class ApiUserMiddleware implements MiddlewareInterface
{
    /**
     * @var ContainerInterface
     */
    protected $container;
    /**
     * @var RequestInterface
     */
    protected $request;

    /**
     * @var HttpResponse
     */
    protected $response;

    protected array $guards = [null];

    #[Inject(AuthManager::class)]
    protected AuthManager $auth;

    public function __construct(ContainerInterface $container, HttpResponse $response, RequestInterface $request)
    {
        $this->container = $container;
        $this->request = $request;
        $this->response = $response;
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $guard = $this->auth->guard('jwt');
        if(!$guard->check()) {
            return $this->response->json([
                'code'=> 401,
                'success'=> false,
                'message'=> '登录失效，请重新打开'
            ]);
        }
        $user = $guard->user();
        
        if ($user) {
            $this->request->user = $user;
            return $handler->handle($request);
        }

        return $this->response->json([
            'code'=> 401,
            'success'=> false,
            'message'=> '登录失效，请重新打开'
        ]);
    }
}